package com.example.easytraffic.core;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

public class RandomPeriodicTraffic implements Traffic{

	private TimeUnit randomPeriodTimeUnit;
	private Traffic traffic;
	private Timer timer;
	private long periodLimit;
	
	public RandomPeriodicTraffic(Traffic traffic,
			long periodLimit,
			TimeUnit randomPeriodTimeUnit) {
		super();
		this.periodLimit = periodLimit;
		this.timer = new Timer();
		this.randomPeriodTimeUnit = randomPeriodTimeUnit;
		this.traffic = traffic;
	}

	public void run() {
		try {
			long periodLimitInMillis = randomPeriodTimeUnit.toMillis(periodLimit);
			long randomPeriod = (long) (Math.random() * periodLimitInMillis);
			long periodInMillis = randomPeriodTimeUnit.toMillis(randomPeriod);
			timer.schedule(new TimerTask() {
				public void run() {
					traffic.run();
				}
			}, 0, periodInMillis);
		} catch (TrafficEndedException e) {
			stop();
		}
	}
	
	public void stop() {
		timer.cancel();
	}
}
